package com.ja.openchat.viewmodels;

import android.app.Application;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.me.EditUserHomePageFragment;
import com.ja.openchat.ui.me.MyFollowPagerGroupFragment;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.BlogInfo;
import com.zy.openchat.core.model.circle.BlogListInfo;
import com.zy.openchat.core.model.circle.BlogUserInfo;
import com.zy.openchat.core.model.circle.CircleVisibleType;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.file.FileInfo;
import com.zy.openchat.core.model.file.FileTaskInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.OrgUserInfo;
import com.zy.openchat.core.model.user.UserFullInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastUtils;


public class MyAlbumViewModel extends PagedViewModel<MyAlbumItemViewModel, BlogInfo> {
    int[] ids = {R.mipmap.zdy_1, R.mipmap.zdy_2, R.mipmap.zdy_3, R.mipmap.zdy_4, R.mipmap.zdy_5};
    public ObservableField<UserInfo> userAvatar = new ObservableField<>();
    public ObservableField<String> userName = new ObservableField<>();
    public ObservableField<String> userIntro = new ObservableField<>();
    public ObservableField<String> blogs = new ObservableField<>();
    public ObservableField<String> fans = new ObservableField<>();
    public ObservableField<String> likes = new ObservableField<>();
    public ObservableField<String> follows = new ObservableField<>();
    public ObservableField<Boolean> isSelf = new ObservableField<>(true);
    public ObservableField<String> buttonTitle = new ObservableField<>(getApplication().getString(R.string.send_a_message));
    public SingleLiveEvent<String> showDialogSingleLiveEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Integer> msgSingleLiveEvent = new SingleLiveEvent<>();

    public MyAlbumViewModel(@NonNull Application application) {
        super(application);
    }

    @Override
    public void requestData(int page) {
        if (page == 1) {
            loadUnReadInfo();
        }
        requestData1(currentBlogId, page);
    }

    @Override
    public int initContentView() {
        return R.layout.item_my_album;
    }


    //编辑主页的点击事件
    public BindingCommand editOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isSelf.get()) {
                startContainerActivity(EditUserHomePageFragment.class.getCanonicalName());
            } else {
                sendMsg();
            }
        }
    });
    public BindingCommand dtOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (mBlogUserInfo != null) {
                showDialogSingleLiveEvent.setValue(String.format(getApplication().getString(R.string.total_dyna_text), mBlogUserInfo.blogs));
            }

        }
    });
    public BindingCommand flOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Bundle bundle = new Bundle();
            bundle.putInt("type", 0);
            bundle.putLong("userId", mUserId);
            startContainerActivity(MyFollowPagerGroupFragment.class.getCanonicalName(), bundle);
        }
    });
    public BindingCommand fsOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Bundle bundle = new Bundle();
            bundle.putInt("type", 1);
            bundle.putLong("userId", mUserId);
            startContainerActivity(MyFollowPagerGroupFragment.class.getCanonicalName(), bundle);
        }
    });
    public BindingCommand zanOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (mBlogUserInfo != null) {
                showDialogSingleLiveEvent.setValue(String.format(getApplication().getString(R.string.total_like_text), mBlogUserInfo.likes));
            }
        }
    });

    public void setData(Bundle bundle) {
        if (bundle != null) {
            mUserId = bundle.getLong("userId", UserInfo.getUserInfo().id);
        } else {
            mUserId = UserInfo.getUserInfo().id;
        }
        isSelf.set(UserInfo.getUserInfo().id == mUserId);
        buttonTitle.set(isSelf.get()?getApplication().getString(R.string.edit_home):getApplication().getString(R.string.send_a_message));
    }

    private long currentBlogId = 0;
    private BlogUserInfo mBlogUserInfo;
    private UserFullInfo userFullInfo;
    private OrgUserInfo orgUserInfo;
    public long mUserId;

    private void requestData1(long from_blog_id, int page) {
        if (page == 1)
            from_blog_id = 0;
        if (from_blog_id == 0) {
            TelegramManager.getTelegramManager().getBlogUser(getApplication(), mUserId, new TgResultBlock<BlogUserInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, BlogUserInfo obj) {
                    mBlogUserInfo = obj;
                    loadUserInfo();
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }
        TelegramManager.getTelegramManager().getUserFullInfo(getApplication(), mUserId, new TgResultBlock<UserFullInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserFullInfo obj) {
                userFullInfo = obj;
                loadUserInfo();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });

        TelegramManager.getTelegramManager().requestOrgContactInfo(getApplication(), mUserId, new TgResultBlock<OrgUserInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, OrgUserInfo obj) {
                orgUserInfo = obj;
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
        int limit = 20;
        if (from_blog_id == 0 && !Common.isEmpty(observableList)) {
            if (observableList.size() > 20) {
                limit = observableList.size();
            }
        }
        TelegramManager.getTelegramManager().getCircleHistory(getApplication(), new CircleVisibleType(mUserId), from_blog_id, limit, new TgResultBlock<BlogListInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, BlogListInfo obj) {
                if (obj != null) {
                    if (obj.blogs != null && obj.blogs.size() > 0)
                        currentBlogId = obj.blogs.get(obj.blogs.size() - 1).id;
                    finishRefreshAndLoad(page, obj.blogs, MyAlbumItemViewModel.class);
                } else {
                    finishRefreshAndLoad(page, null, MyAlbumItemViewModel.class);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                finishRefreshAndLoad(page, null, MyAlbumItemViewModel.class);
            }
        });
        getLoginOrgUserInfo();
    }

    private void loadUnReadInfo() {
        if (UserInfo.getUserInfo().id != mUserId) {
            return;
        }
        int count = TelegramManager.getTelegramManager().mCircleUnreadCount;
        msgSingleLiveEvent.setValue(count);
    }

    private void loadUserInfo() {
        UserInfo userInfo = UserInfo.getUserInfo(mUserId);
        if (userInfo != null) {
            userAvatar.set(userInfo);
            userAvatar.notifyChange();
            userName.set(userInfo.displayName());
        }
        if (mBlogUserInfo != null) {
            blogs.set(String.format("%d%s", mBlogUserInfo.blogs,getApplication().getString(R.string.dynamic_text)));
            fans.set(String.format("%d%s", mBlogUserInfo.fans,getApplication().getString(R.string.fan_text)));
            likes.set(String.format("%d%s", mBlogUserInfo.likes,getApplication().getString(R.string.liked_text)));
            follows.set(String.format("%d%s", mBlogUserInfo.follows,getApplication().getString(R.string.unfocus_text)));
        }
        if (userFullInfo != null) {
            userIntro.set(userFullInfo.bio);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(TgEvent tg_event) {
        if (tg_event == null || tg_event.data == null) {
            return;
        }
        switch (tg_event.event) {
            case EUser_Td_Message_Photo_Ok:
            case EUser_Td_Message_Video_Ok:
                if (tg_event.data instanceof FileTaskInfo && tg_event.dataEx instanceof FileInfo) {
                    FileInfo fileInfo = (FileInfo) tg_event.dataEx;
                    String ids = ((FileTaskInfo) tg_event.data).id;
                    if (!TextUtils.isEmpty(ids) && ids.contains("_")) {
                        String[] idArray = ids.split("_");
                        if (idArray.length > 1) {
                            for (int i = 0; i < observableList.size(); i++) {
                                BlogInfo blogInfo = ((MyAlbumItemViewModel) observableList.get(i)).circleInfo;
                                boolean isVideoDownedd = blogInfo.isVideoDownloadEnough();

                                if (idArray[1].equals(String.valueOf(blogInfo.id))) {
                                    switch (tg_event.event) {
                                        case EUser_Td_Message_Photo_Ok:
                                            blogInfo.updatePhotoFile(fileInfo);
                                            break;
                                        case EUser_Td_Message_Video_Ok:
                                            blogInfo.updateVideoFile(fileInfo);
                                            break;
                                    }
                                    KLog.d("update==111----" + tg_event.event + i);

                                    if (tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Video_Ok && isVideoDownedd) {
                                        return;
                                    }
//                                    KLog.d("update==" + tg_event.event + i);
//                                    observableList.set(i, new MyAlbumItemViewModel(this, blogInfo));
                                    String mediaUrl = ((MyAlbumItemViewModel) observableList.get(i)).getMediaUrl();
                                    KLog.d("update mediaUrl==  " + i + mediaUrl);
                                    break;
                                }
                            }
                        }
                    }
                }
                break;
            case EUser_Td_Delete_Blog:
                if (tg_event.data != null && tg_event.data instanceof Long) {
                    long blogId = (Long) tg_event.data;
                    for (int i = 0; i < observableList.size(); i++) {
                        if (((MyAlbumItemViewModel) observableList.get(i)).circleInfo != null
                                && blogId == ((MyAlbumItemViewModel) observableList.get(i)).circleInfo.id) {
                            observableList.remove(i);
                            break;
                        }
                    }
                }
                break;
            case EUser_Td_Contact_Photo_Ok:
            case EUser_Td_UpdateContactInfo:
                if ((tg_event.data instanceof UserInfo)) {
                    UserInfo userInfo = (UserInfo) tg_event.data;
                    if (userInfo.id == mUserId) {
                        loadUserInfo();
                    }
                }
                break;
            case EUser_Td_Chat_User_Full_Info:
                if (tg_event.data instanceof Long) {
                    if (mUserId == ((Long) tg_event.data)) {
                        if (tg_event.dataEx != null && tg_event.dataEx instanceof UserFullInfo) {
                            userFullInfo = (UserFullInfo) tg_event.dataEx;
                            loadUserInfo();
                        }
                    }
                }
                break;
            case EUser_Td_UpdateUserInfo:
                loadUserInfo();
                break;
            case EUser_Td_update_Circle_Unread_count:
                loadUnReadInfo();
                break;

        }
    }
    private OrgUserInfo loginOrgUserInfo;
    private void getLoginOrgUserInfo(){
//        TelegramManager.getTelegramManager().requestOrgContactInfo(getApplication(), UserInfo.getUserInfo().id, new TgResultBlock<OrgUserInfo>() {
//            @Override
//            public void onResult(Map<String, Object> request, JsonObject response, OrgUserInfo obj) {
//                loginOrgUserInfo = obj;
//            }
//
//            @Override
//            public void onTimeout(Map<String, Object> request) {
//            }
//        });
    }

    private boolean canSendMsg() {
        if(loginOrgUserInfo!=null&&loginOrgUserInfo.isInternal){
            return true;
        }
        UserInfo user = UserInfo.getUserInfo(mUserId);
        if (user != null) {
            if (user.is_contact) {//已经是好友的，不受任何影响
                return true;
            }
            AppConfigInfo info = AppConfigInfo.getAppConfigInfo();
            if (info != null) {
                if (info.onlyWhiteAddFriend) {
                    return false;
                }
                if (info.onlyFriendChat) {//加好友才能聊天
                    return user.is_contact;
                }
            }
            return true;
        }
        return false;
    }

    void sendMsg() {
        if(!canSendMsg()){
            ToastUtils.showShort(getApplication().getString(R.string.other_not_friend_first_add));
            return;
        }
        TelegramManager.getTelegramManager().createPrivateChat(getApplication(), mUserId, new TgResultBlock<ChatInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, ChatInfo obj) {
                if (obj != null) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("conversation", obj);
                    startActivity(ChatActivity.class, bundle);
                }

            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        KLog.d("onResume");
        loadUnReadInfo();
        TelegramManager.getTelegramManager().getCircleUnreadCount();
        currentBlogId = 0;
        requestData1(currentBlogId, 1);
    }

    @Override
    public boolean showEmpty() {
        return false;
    }
}
